package com.rech.xbexpress3;
import com.rech.xbexpress3.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rech.utils.OtherUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 寄件信息确认页
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Jj4Activity extends AppCompatActivity {
    String jj_sfz;
    String jj_name;
    String jj_sjh;
    int expType;
    String jj_kdysj;
    String jj_ljm;
    String jj_sjr;
    String jj_gridtype;
    String jj_gridnum;
    String jj_cabinetgridid;
    Button jj4_cxkg;
    private CountDownTimer mTimer=null; //UI业务倒计时
    private TextView djs ;
    private Timer countTimer;
    private int yym_count = 0;
    private long jj4_clicktime = 0;
    private int jjcount = 20;
    public static final long TIME_INTERVAL = 2000L;
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)

        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };
    private String jjr_address;
    private String sjr_address;
    private String kdy_id;
    private String wl_id;
    private String order_id;
    private boolean isFromWX = false;
    private LinearLayout ll_sjr;
    private LinearLayout ll_ljm;
    private LinearLayout ll_kdy;

    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
    private void Exit(){
        unInitTimer();
        countTimer.cancel();
        EventBus.getDefault().unregister(this);
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFromWX = getIntent().getBooleanExtra("isFromWX", false);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            setContentView(R.layout.activity_jj4_land);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setContentView(R.layout.activity_jj4);
        }

        jjcount = 20;
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //setContentView(R.layout.activity_jj4);
        djs = findViewById(R.id.tv_djs);
        mVisible = true;getSupportActionBar().hide();

        jj_sfz  =  sharedPreferences.getString("jj_sfz", "");
        jj_name = sharedPreferences.getString("jj_name", "");
        jj_sjh  =  sharedPreferences.getString("jj_sjh", "");
        expType     =  sharedPreferences.getInt("jj_exp",0);
        jj_kdysj =  sharedPreferences.getString("jj_kdysj", "");
        //jj_ljm   = sharedPreferences.getString("jj_ljm1", "") + "-" + sharedPreferences.getString("jj_ljm2", "");
        jj_ljm   = sharedPreferences.getString("jj_ljm1", "");
        jj_sjr   = sharedPreferences.getString("jj_sjr", "");
        //jj_gridtype = sharedPreferences.getString("jj_gridtype","");
        jj_gridnum = sharedPreferences.getString("jj_gridnum","");
        jj_cabinetgridid = sharedPreferences.getString("jj_cabinetgridid","");
        jjr_address = sharedPreferences.getString("jj_jjr_address","");
        sjr_address = sharedPreferences.getString("jj_sjr_address","");
        kdy_id = sharedPreferences.getString("kdy_id","");
        wl_id = sharedPreferences.getString("wl_id","");
        order_id = sharedPreferences.getString("jj_wx_orderId","");
        TextView wdsj = (TextView)findViewById(R.id.jj4_wdsj);
        wdsj.setText(jj_sjh);
        TextView ljm = (TextView)findViewById(R.id.jj4_ljm);
        ljm.setText(jj_ljm);

        TextView kdysj = (TextView)findViewById(R.id.jj4_kdysj);
        kdysj.setText(jj_kdysj);

        //TextView sjr = (TextView)findViewById(R.id.jj4_sjr);
        //sjr.setText(jj_sjr);
        TextView gmxx = (TextView)findViewById(R.id.jj4_gmxx);
        gmxx.setText(jj_gridnum);
        TextView gzdz = (TextView)findViewById(R.id.jj4_gzdz);
        gzdz.setText(sharedPreferences.getString("CabinetType_address", ""));
        //TextView jj4_qx = (TextView) findViewById(R.id.tv_back);

        //ll_sjr = (LinearLayout) findViewById(R.id.ll_sjr);
        ll_ljm = (LinearLayout) findViewById(R.id.ll_ljm);
        ll_kdy = (LinearLayout) findViewById(R.id.ll_kdy);
        if (jj_ljm.equals("-")) {
            //ll_sjr.setVisibility(View.GONE);
            ll_ljm.setVisibility(View.GONE);
            ll_kdy.setVisibility(View.GONE);
        }

        /*jj4_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("isFromCainiao", jj_ljm.equals("-")?false:true);
                intent.putExtra("isFromWX", isFromWX?1:0);
                setResult(1004, intent);

                Exit();
                finish();
            }
        });*/

        Button jj4_qr = (Button) findViewById(R.id.jj4_qr);
        jj4_qr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - jj4_clicktime > TIME_INTERVAL) {
                    jj4_clicktime = nowTime;
                    int cabinetgridid = Integer.parseInt(jj_cabinetgridid);
                    if (isFromWX) {
                        new FetchConfirmOrder(order_id,cabinetgridid,kdy_id,wl_id).execute();
                    } else {
                        new FetchBillTask(jj_sfz,jj_name,jj_sjh,cabinetgridid,jj_ljm,jj_sjr,jj_kdysj,expType,jjr_address,sjr_address,kdy_id,wl_id).execute();
                    }
                }
            }
        });


        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phone);

        Button jj4_cxgz = (Button) findViewById(R.id.jj4_cxgz);
        jj4_cxgz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - jj4_clicktime > TIME_INTERVAL) {
                    jj4_clicktime = nowTime;
                    OtherUtil.OpenVoice4(Jj4Activity.this);

                    //添加重选格子标志位
                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putBoolean("isReChoose",true);
                    editor.apply();

                    Intent intent = new Intent();
                    intent.putExtra("isFromCainiao", jj_ljm.equals("-")?false:true);
                    intent.putExtra("isFromWX", isFromWX?1:0);
                    setResult(1004, intent);
                    Exit();
                    finish();

                }
                //startActivity(new Intent(FullscreenActivity.this, FaceActivity.class));
            }
        });
        //initTimer();
        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                //djs.setText(String.valueOf(OtherUtil.jjcount));
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    int cabinetgridid = Integer.parseInt(jj_cabinetgridid);
                    if (isFromWX) {
                        new FetchConfirmOrder(order_id,cabinetgridid,kdy_id,wl_id).execute();
                    } else {
                        new FetchBillTask(jj_sfz,jj_name,jj_sjh,cabinetgridid,jj_ljm,jj_sjr,jj_kdysj,expType,jjr_address,sjr_address,kdy_id,wl_id).execute();
                    }

                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putString("jj_sjr_address","");
                    editor.putString("jj_jjr_address","");
                    editor.putString("kdy_id","");
                    editor.putString("wl_id","");
                    editor.putString("jj_kdysj","");
                    editor.putString("jj_ljm1","");
                    //editor.putString("jj_ljm2","");
                    editor.putString("jj_sjr","");
                    editor.apply();

                    Exit();
                    finish();
                }

            }
        },0,1000);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        OtherUtil.OpenVoice8(Jj4Activity.this);
                    }
                }, 5000);
            }
        });
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay

    }

    @SuppressLint("InlinedApi")
    private void show() {
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay

    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    /*private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!Jj4Activity.this.isFinishing()) {
                        if(yym_count != 0){
                            if(yym_count > 1){
                                yym_count = yym_count -1;
                                String strText = "重新开柜("+String.valueOf(yym_count)+")";
                                jj4_cxkg.setText(strText);
                            }else{
                                jj4_cxkg.setText("重新开柜");
                                yym_count = 0;
                            }
                        }

                        int remainTime = (int) (millisUntilFinished / 1000L);
                        Log.e("zpan", "======remainTime=====" + remainTime);

                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }*/

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){

            case 10110:
                handleBillTask(message.obj);
                break;
            case 10111:
                Toast.makeText(Jj4Activity.this, "下单失败", Toast.LENGTH_SHORT).show();
                break;
            case 10112:
                handleReOpenTask(message.obj);
                break;
            case 10113:
                Toast.makeText(Jj4Activity.this, "网络异常,重新开柜失败", Toast.LENGTH_SHORT).show();
                break;
            case 20000:
                handleDJS();
                break;
        }
    }
    public void handleBillTask(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("jj_sjr_address","");
                editor.putString("jj_jjr_address","");
                editor.putString("kdy_id","");
                editor.putString("wl_id","");

                editor.putString("jj_kdysj","");
                editor.putString("jj_ljm1","");
                //editor.putString("jj_ljm2","");
                editor.putString("jj_sjr","");
                editor.apply();

                Intent intent = new Intent();
                //intent.putExtra("sn", resultString);
                setResult(1006, intent);
                Exit();
                finish();
            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }
    public void handleReOpenTask(Object obj){
        try {
            JSONObject result = new JSONObject(obj.toString());
            if (result.getString("code").equals("100")) {
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                OtherUtil.OpenVoice2(this);
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        Intent intent = new Intent();
                        //intent.putExtra("sn", resultString);
                        setResult(4012, intent);
                        t.cancel();
                    }
                }, 2000);

            } else {
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);

            }

        } catch (Exception e) {
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }
    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }
}
